#/bin/python
#coding:utf8
'''
Created on 2011-4-30

@author: mark
'''
from __future__ import with_statement
import web
import config


db = config.database    
mc = config.memcache_client

def createproblem(_title, _pdesc, _uid, _type, _autoclose, _pbComment):
    pid = db.insert('problem', title=_title, asker=_uid, pdesc=_pdesc, type=_type, auto_close=_autoclose, pb_comment=_pbComment)
    return pid
   
        
def modifyproblem(pid, _title, _pdesc, _type):
    db.update("problem", where="pid = %s" % pid , title=_title, pdesc=_pdesc, type=_type)

def getproblembyid(pid):
    key = str("prob_%s" % pid)
    problem = mc.get(key)
    if not problem:
        problem = _getproblembyid(pid)
        if problem:
            mc.set(key, problem, config.cache_timeout)
    return problem
        
def _getproblembyid(pid):
    result = db.select('problem', where="pid = %s" % pid)
    if result:
        return result[0]
    else:
        return []
    
def closeproblem(pid, _last_answer):
    key = str("prob_%s" % pid)
    mc.delete(key)
    q = db.update('problem', where="pid=%s" % pid, close_time=web.SQLLiteral("NOW()"), last_answer=_last_answer)
    return q

def addAutoCloseProblem(pid, expect_time):
    db.insert('auto_close_problem', pid=pid, expect_time=expect_time)

def modifyAutoCloseProblem(pid, expect_time):
    db.update("auto_close_problem", where="pid=%s" % pid, expect_time=expect_time)

def getProblemsByType(tid, start):
    problems = db.query("select p.asker as asker,p.pid as pid,p.title as title,p.choicecount as choicecount , p.comentcount as comentcount ,t.name as tname ,t.tid as tid from problem p inner join type t on p.type = t.tid and t.tid = %s limit %s,%s" % (tid, start, config.pagesize))
    if problems:
        return problems
    else:
        return []

def getMyProblems(uid, start):
    problems = db.select("problem" , where="asker=%s" % uid, offset=start, limit=config.pagesize)
    if problems:
        return problems
    else:
        return []

#problems for the userhome page 
def getMyProblemsForUserhome(uid, start):
    problems = db.query("select p.choicecount as ccount,p.pid as pid, p.title as title ,p.enable as pstatus ,p.comentcount as comentcount ,DATEDIFF(p.expect_time,now()) as expect_time, t.name as tname,t.tid as tid from problem p inner join hc.type t on t.tid = p.type where p.asker = %s order by create_time limit %s,%s" % (uid, start, config.pagesize))
    if problems:
        return problems
    else:
        return []

def addfocutProblem(uid, pid):
    res = db.insert('focus_problem', uid=uid, pid=pid)
    return res

def getProblemByUser(uid):
    res = db.select("problem", where="asker= %d" % uid)
    if res:
        return res
    else:
        return []
    
def getFocusProblemsByUser(uid):
    res = db.select("focus_problem", where="uid = %d" % uid)
    if res:
        return res
    else:
        return []
    
def updateProblemAutoComplete(pid, expect_time):
    res = db.update("problem", where="pid = %s" % pid , auto_close=1, expect_time=expect_time)
    if res:
        return res
    else:
        return []
    
def updateProblemPubComment(pid, _pb_comment):
    res = db.update("problem", where="pid = %s" % pid, pb_comment=_pb_comment)
    if res:
        return res
    else:
        return []
    
def getNewProblem(count):
    problems = db.select(['problem', 'user'], where="problem.asker = user.uid", order="problem.create_time desc" , limit=count)
    
    def cutHtml(p):
        _desc = p.pdesc[0:100]
        p.pdesc = _desc
        return p
    
    return [cutHtml(p) for p in problems]

    
def getAllProblems(start):
    problems = db.query("select p.pid as pid,p.title as title,p.choicecount as choicecount , p.comentcount as comentcount ,t.name as tname ,t.tid as tid from problem p inner join type t on p.type = t.tid limit %s,%s" % (start, config.pagesize))
    return problems

def getMyProblemCount(uid):
    count = db.query("select count(*) as count from problem where asker = %s" % uid)
    if count:
        return count[0]['count']
    else:
        return 0
    
def getMyFocusProblem(uid, start):
    problems = db.query("select p.pid as pid ,p.title as title , t.name as tname, t.tid as tid ,DATEDIFF(expect_time,now()) as expect_time,p.comentcount as comentcount , p.choicecount as ccount ,p.enable as pstatus ,an.rank as rank from problem p inner join answer an on p.pid = an.pid inner join hc.type t on p.type = t.tid where an.answor = %s limit %s,%s" % (uid, start, config.pagesize))
    if problems:
        return problems
    else:
        return []   

        
import time
from datetime import date

def _getMonthHotProblems(count):
    _today = date.today()
    current_year = _today.year
    current_month = _today.month
    
    if current_month == 12:
        next_year = current_year + 1
        next_month = 1
    else:
        next_year = current_year
        next_month = current_month + 1
        
    problems = db.select("problem" , where="create_time >= $pre_month and create_time < $next_month ", vars=dict(pre_month="%s-%s-1" % (current_year, current_month), \
                                                                                                               next_month="%s-%s-1" % (next_year, next_month)), \
                                                                                                               order="(comentcount+choicecount) desc", \
                                                                                                               limit=count)
    return problems
 
getMonthHotProblems = web.memoize(_getMonthHotProblems, config.month_func_cache)

def _getWeekHotProblems(count):
    weekday = time.strftime("%w", time.localtime())
    prev, next = int(weekday), 7 - int(weekday)
    
    problems = db.query("select * from problem where create_time >= DATE_ADD(NOW(),INTERVAL -%s DAY) and create_time < DATE_ADD(NOW(),INTERVAL %s DAY) order by (comentcount+choicecount) desc limit %s" % (prev, next, count))
    return problems
 
getWeekHotProblems = web.memoize(_getWeekHotProblems, config.week_func_cache)

def addCommentCountByPid(pid):
    res = db.query("update problem set comentcount = comentcount+1 where pid = %s" % pid)
    return res == 1

def addChoiceCountByPid(pid):
    res = db.query("update problem set choicecount = choicecount+1 where pid = %s" % pid)
    return res == 1 
